import Store from 'common/Store'
import Utils from 'common/Utils'
import Http from 'common/Http'
export default class Login {

  static _ins: Login
  static get instance(): Login {
    return this._ins || new Login;
  }
  constructor() {
    Login._ins = this
  }

  moduleName = 'Login'

  /**
   * 到期时间 30分钟
   */
  expire: number = 60 * 60 * 1000 * .5

  /**
   * 是否登录
   */
  _isLogin: boolean = false;

  /**
   * 是否选角
   */
  _isRole: boolean = false;

  /**
   * 判断是否已登录
   */
  isLogin() {
    if (Store.instance.map.userInfo) {
      var { userId, token, activetime } = Store.instance.map.userInfo
      if (userId && token) {
        var active = new Date().getTime() - this.expire;
        if (activetime && active < activetime * 1) {
          return true
        } else {
          Store.instance.clear()
        }
      }
    }
    return false;
  }

  /**
   * 是否选择了角色
   */

  isRole() {
    if (Store.instance.map.zoneInfo && Store.instance.map.roleInfo) {
      return true
    }
    return false
  }

  checkFbLogin() {
    var fbCode = Utils.instance.getParameterByName('code')
    if (!fbCode) {
      return false
    }
    var promise = $.Deferred()

    Http.instance.fbLogin(fbCode).then(data => {
      promise.resolve(data)
    }).fail(err => {
      promise.resolve({
        code: 400,
        state: err
      })
    })

    return promise
  }

  /**
   * fb登录
   */
  fbLogin() {
    var loginUrl = `//www.facebook.com/v2.6/dialog/oauth?client_id=${Store.instance.map.fbId}&redirect_uri=${encodeURIComponent(Store.instance.map.fbRedirectUrl)}&r=${Utils.instance.random}`
    location.href = loginUrl;
  }

  /**
   * 平台登录
   */
  pfLogin(): JQuery.Deferred<EventData> {
    var promise = $.Deferred()
    var userName = window.username.value // = 'Qiong@9266.com'
    var password = window.password.value // = 'qqqqqq'
    password = md5(password, 32)
    var version = Store.instance.map.version
    if (!userName || !password) {
      promise.resolve({
        code: 400,
        state: window.translation.loginInfoErr
      })
    } else {
      Http.instance.pfLogin({
        userName,
        password,
        version
      }).then(data => {
        promise.resolve(data)
      }).fail(err => {
        promise.resolve({
          code: 400,
          state: err
        })
      })
    }
    return promise
  }


}